console.log($event,'节点双击')
const baseWidget = this.getApiPage().getApiWidgetByAliasName('三维组件');
const videoPageWidgets = this.getApiPage().getApiWidgetByAliasName('视频分页组件');
// 获取变量
var stream_url = this.getApiPage().getVariables().find(x => x.name == "stream_url").value;
const devices = this.pageObj.getApiWidgetByAliasName('devices');
const { dataSource } = devices.widgetObj._option;
// const api = 'http://192.168.1.100:9098/basics-main/system/equipmentObject/listDetailByEquipmentCode'
// const api = '/Basics/basics-main/system/equipmentObject/listDetailByEquipmentCode';
const api = '/Basics/basics-main/system/equipmentObject/listDetailByEquipmentCodeByOnlineStatus'
const sullivan = baseWidget?.widgetObj?.sullivan;
const params = { ...$event };

function baseGet(url) {
    const headers = { "Content-Type": "application/json" };
    return fetch(url, { headers }).then(res => res.json());
}
console.log('dataSource: => ', dataSource);
console.log('params: => ', params);

function filterCameras(cameras) {
    // 可以播放的列表
    const cameraSure = new Map();
    // 原始列表
    const __cameras = cameras.map((camera) => {
        const { equipmentConfig, equipmentName } = camera;

        camera.title = equipmentName;
        if (equipmentConfig?.gbVideoConfig) {
            const { sipUser, videoChannelId, sipServerHost, sipServerPort } = equipmentConfig.gbVideoConfig;
            camera.stream_path = `${sipUser}/${videoChannelId}`;
            camera.channelId = videoChannelId;
            camera.deviceId = sipUser;
            camera.host = `${sipServerHost}:${sipServerPort}`;

            // 过滤出有媒体配置，可以播放的。
            cameraSure.set(`${sipUser}/${videoChannelId}`, camera)
        }

        return camera
    });

    return [__cameras, [...cameraSure.values()]]
}

function findItem(datas, id) {
    let children = [];
    let item = datas.find(item => {
        if (item.children?.length) children = children.concat(item.children);
        return item.id === id
    });

    if (!item && children.length) item = findItem(children, name);

    return item
}

function resetDataSource(dataSource, cameraList, id) {
    const listItem = findItem(dataSource, id);

    // 定义缓存
    listItem.catch = new Map();
    if (!listItem.catchItems) listItem.catchItems = new Map();

    // 清空列表
    listItem.children.length = 0;

    cameraList.forEach(item => {
        if (!listItem.catchItems.has(item.id)) {
            listItem.catchItems.set(item.id, item);
        }
        listItem.children.push(item);
    });

    listItem.catch.set(id, cameraList);
    console.log(dataSource, listItem, id);
    return dataSource
}

// 默认16分屏
sullivan?.resizeSullivan(16);

const $wrapper = $(`#sullivan-display .swiper-wrapper`);
const wrapCls = $wrapper.data('class');
// 获取视频组件的分屏数并保存到window上
const gridSize = $(`#sullivan-display .swiper-wrapper .swiper-slide`).length;
window.videoCurrentGridSize = gridSize;
let cls;
if (gridSize === 16) {
    cls = 'grid-4x4'
} else if (gridSize === 20) {
    cls = 'grid-5x4'
} else if (gridSize === 9) {
    cls = 'grid-3x3'
} else if (gridSize === 4) {
    cls = 'grid-2x2'
} else if (gridSize === 2) {
    cls = 'grid-1x1'
}
$wrapper.data('class', cls).removeClass(wrapCls).addClass(cls);

if (params.id.indexOf('off') === -1) {
    // `${api}?equipmentCode=camera&areaId=&pageSize=1&pageNum=1`
    baseGet(`${api}?equipmentTypeCode=camera&areaId=${params.id}&onlineStatus=0`).then(({ success, result = [] }) => {
        if (success) {
            const [cameraList, cameraSure] = filterCameras(result.rows);

            // resetDataSource(dataSource, cameraList, params.id);
            console.log('vvvvvvvvvvvvvvvv', dataSource, result.rows);

            // 清空已存在的摄像头
            sullivan?.closeAll(true);

            // 获取当前区域节点下所有摄像头信息并存到window上
            const $sullivan = $("#sullivan-display");
            let $container = $("#sullivan-page-container");
            if (!$container.length) {
                $container = $('<div id="sullivan-page-container"></div>');
                $sullivan.find('.card-panel-footer')
                    .append($container)
                    .append(`
        <style id="sullivan-style">
          #sullivan-display .card-panel-footer {
            position: relative;
          }
          #sullivan-page-container {
            position: absolute;
            top: 0;
            left: 50%;
            width: 300px;
            height: 100%;
            transform: translateX(-50%);
            display: flex;
            justify-content: center;
          }
          #sullivan-display .lay-page-container {
            height: 100%;
          }
        </style>
      `);
            }

            window.videoCurrentSelectArea = cameraSure;
            videoPageWidgets.widgetObj._option.count = cameraSure.length;
            sullivan?.insertWidget(videoPageWidgets, $container);
            videoPageWidgets.widgetObj.setLimit(16);

            if (Array.isArray(cameraSure)) {
                // 设备当前分页数默认为1并保存到window上
                window.videoCurrentPagenum = 1;
                console.log(gridSize, 'gridSize');

                // 根据当前分页和分屏获取当前要展示的视频
                const start = (window.videoCurrentPagenum - 1) * window.videoCurrentGridSize;
                const end = start + window.videoCurrentGridSize;
                // 截取第一页显示的视频个数。
                const currentVideos = cameraSure.slice(start, end);
                currentVideos.map((item, i) => {
                    console.log(item);
                    if (item.host) {
                        item.equipmentId = item.equipmentCode;

                        return sullivan?.addPlayerWidthData(`${window.location.origin}/streamUrl/api/v1/stream/rtc/play`, item, i)
                    } else {
                        return window.layer?.msg('摄像头未找到配置！');
                    }
                })
            }
        }
    });
}